package com.ruoyi.crop.controller;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.crop.api.domain.OutBound;
import com.ruoyi.crop.api.domain.SignRecord;
import com.ruoyi.crop.api.domain.Warehouse;
import com.ruoyi.crop.service.OutBoundService;
import com.ruoyi.crop.service.SignRecordService;
import com.ruoyi.crop.service.WarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/out")
public class OutBoundController extends BaseController {

    @Autowired
    private OutBoundService outBoundService;

    @Autowired
    private SignRecordService signRecordService;

    @Autowired
    private WarehouseService warehouseService;

    @GetMapping("list")
    public TableDataInfo list(OutBound outBound){

        startPage();
        List<OutBound> list = outBoundService.listAll(outBound);
        return getDataTable(list);
    }
    @GetMapping("list1")
    public TableDataInfo list1(OutBound outBound){

        startPage();
        List<OutBound> list = outBoundService.listAll1(outBound);
        return getDataTable(list);
    }
    
    @RequiresPermissions("crop:out:remove")
    @Log(title = "删除管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids){

        outBoundService.deleteDictTypeByIds(ids);
        return success();
    }

    //签收
    @Transactional
    @PostMapping("add")
    public AjaxResult add(@RequestBody OutBound outBound){

        Warehouse warehouse = warehouseService.getById(outBound.getWarehouseId());
        if(Integer.valueOf(warehouse.getWarehouseUsable()) < Integer.valueOf(outBound.getNumber())){
            return error("仓库容量不足");
        }
        SignRecord signRecord = new SignRecord();
        signRecord.setWarehouseId(outBound.getWarehouseId());
        signRecord.setProductName(outBound.getProductName());
        signRecord.setCreateTime(new Date());
        signRecord.setNumber(outBound.getNumber());
        signRecord.setAddress(outBound.getOutboundParty());
        boolean save = signRecordService.save(signRecord);
        if(save){
            warehouse.setWarehouseUsable(String.valueOf(Integer.valueOf(warehouse.getWarehouseCapacity())-Integer.valueOf(outBound.getNumber())));
            warehouseService.updateById(warehouse);
            outBoundService.delById(outBound.getOutboundId());
        }else{
            throw new RuntimeException("仓库容量不足,签收失败");
        }
        return success();
    }






}
